// FileAnalysisController.java
package com.webguard.outlierdetection.controller;

import com.webguard.outlierdetection.pojo.Result;
import com.webguard.outlierdetection.service.FileAnalysisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/files")
public class FileAnalysisController {
    private static final Logger logger = LoggerFactory.getLogger(FileAnalysisController.class);

    private final FileAnalysisService fileService;

    @Autowired
    public FileAnalysisController(FileAnalysisService fileService) {
        this.fileService = fileService;
    }

    @PostMapping("/upload")
    public ResponseEntity<Result> handleFileUpload(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "format", defaultValue = "auto") String format) {
        try {
            fileService.processUploadedFile(file, format);
            return ResponseEntity.ok(Result.success("文件已接收并开始处理"));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(Result.error(e.getMessage()));
        } catch (Exception e) {
            logger.error("文件处理失败: {}", file.getOriginalFilename(), e);
            return ResponseEntity.internalServerError().body(Result.error("文件处理失败"));
        }
    }
}
